<template>
    <el-dialog ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="60%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <template v-if="addEditFlag == 'add'">
                <el-form-item label="选择疾病" prop="diseaseBankId">
                    <el-select class="w100p" :disabled="addEditFlag == 'edit'" v-model="ruleForm.diseaseBankId"
                        placeholder="请选择疾病" filterable clearable>
                        <el-option v-for="item, index in diseaseList" :key="index" :label="item.diseaseName"
                            :value="item.diseaseBankId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="关联鱼塘" prop="fishPondId">
                    <el-select v-model="ruleForm.fishPondId" filterable clearable class="w100p"
                        @change="handleChangeFishPond">
                        <el-option v-for="(item, index) in fishPondList" :key="index" :label="item.pondName"
                            :value="item.fishPondId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择批次" prop="batchId">
                    <el-select v-model="ruleForm.batchId" @change="batchPondInfoList(ruleForm.batchId)" filterable clearable class="w100p">
                        <el-option v-if="ruleForm.fishPondId == item.fishPondId" v-for="(item, index) in batchList"
                            :key="index" :label="item.batchName" :value="item.batchId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择品种" prop="fishVarietyId">
                    <el-select :disabled="addEditFlag == 'addAgain'" v-model="ruleForm.fishVarietyId" filterable
                        clearable class="w100p">
                        <el-option v-for="item, index in fishVarietyList" :key="index" :label="item.fishVarietyName"
                            :value="item.fishVarietyId" />
                    </el-select>
                </el-form-item>
            </template>
            <template v-if="addEditFlag !== 'add'">
                <el-form-item label="疾病信息">
                    <div class="w100p infoList">
                        <div class="infoItem">
                            <span class="label">鱼塘名称:</span>
                            <span class="text">{{ ruleForm.fishPondName }}</span>
                        </div>
                        <div class="infoItem">
                            <span class="label">批次编号:</span>
                            <span class="text">{{ ruleForm.batchName }}</span>
                        </div>
                        <div class="infoItem">
                            <span class="label">疾病名称:</span>
                            <span class="text">{{ ruleForm.diseaseName }}</span>
                        </div>
                        <div class="infoItem">
                            <span class="label">发病品种:</span>
                            <span class="text">{{ ruleForm.varietyName }}</span>
                        </div>
                        <div class="infoItem" v-if="addEditFlag !== 'edit'">
                            <span class="label">病鱼数量:</span>
                            <span class="text">{{ ruleForm.num }}尾</span>
                        </div>
                        <div class="infoItem" v-if="addEditFlag !== 'edit'">
                            <span class="label">发现人:</span>
                            <span class="text">{{ ruleForm.findName }}</span>
                        </div>
                        <div class="infoItem" v-if="addEditFlag !== 'edit'">
                            <span class="label">发现日期:</span>
                            <span class="text">{{ ruleForm.findDate }}</span>
                        </div>
                    </div>
                </el-form-item>
            </template>
            <el-form-item v-if="addEditFlag !== 'addAgain'" label="病鱼数量" prop="num">
                <el-input v-model="ruleForm.num" clearable placeholder="请输入数量" type="number" class="w100p">
                    <template slot="append">尾</template>
                </el-input>
            </el-form-item>
            <el-row v-for="item, index in ruleForm.medicineList" :key="index" v-if="addEditFlag !== 'edit'">
                <el-col :span="10">
                    <el-form-item :label="index == 0 ? '药品名称' : ''" :prop="`medicineList[${index}][materialId]`"
                        :rules="rules.materialId">
                        <el-select class="w100p" filterable clearable v-model="item.materialId" placeholder="请选择">
                            <el-option v-for="(m, i) of materialList" :key="i" :label="m.name" :value="m.materialId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item class="noLabel" :prop="`medicineList[${index}][amount]`" :rules="rules.amount">
                        <el-input type="number" v-model="item.amount" placeholder="请输入数量"
                            @change="handleChangeNum(item, index)">
                            <template slot="append">{{ item.materialId ? materialObj[item.materialId].unit : ""
                                }}</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item class="noLabel" :prop="`medicineList[${index}][convertNum]`"
                        :rules="rules.convertNum">
                        <el-input type="number" v-model="item.convertNum" placeholder="请输入数量"
                            @change="handleChangeconvertNum(item, index)">
                            <template slot="append">{{ item.materialId ? materialObj[item.materialId].aUnit :
        "" }}</template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <i class="icon el-icon-circle-plus-outline" @click.stop="addMaterial()"></i>
                    <i v-show="index" class="icon el-icon-remove-outline" @click.stop="delMaterial(index)"></i>
                </el-col>
            </el-row>
            <el-form-item v-if="addEditFlag !== 'addAgain'" label="发现人" prop="findNameId">
                <el-select v-model="ruleForm.findNameId" filterable clearable class="w100p"
                    @change="(id) => { handleChangeStaff(id, 'findName') }">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item label="处理人" prop="dealId" v-if="addEditFlag !== 'edit'">
                <el-select v-model="ruleForm.dealId" filterable clearable class="w100p"
                    @change="(id) => { handleChangeStaff(id, 'dealName') }">
                    <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                        :value="item.staffId" />
                </el-select>
            </el-form-item>
            <el-form-item v-if="addEditFlag !== 'addAgain'" label="发现日期" prop="findDate">
                <el-date-picker v-model="ruleForm.findDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="处理日期" prop="dealDate" v-show="addEditFlag !== 'edit'">
                <el-date-picker v-model="ruleForm.dealDate" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions" class="w100p">
                </el-date-picker>
            </el-form-item>
            <el-form-item :label="addEditFlag == 'edit' ? '' : '历史' + '用药记录'" v-show="addEditFlag !== 'add'">
                <el-table :data="detailList" border style="width: 100%">
                    <el-table-column prop="materialName" label="药品名称">
                        <template slot-scope="scope">
                            <span v-if="scope.row.amount">
                                {{ materialObj[scope.row.materialId].name }}
                            </span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="投喂量(主)">
                        <template slot-scope="scope">
                            <span v-if="scope.row.amount">
                                {{ scope.row.materialId ? scope.row.amount / materialObj[scope.row.materialId].ratioNum
        : "" }}
                                {{ scope.row.materialId ? materialObj[scope.row.materialId].aUnit : "" }}
                            </span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="投喂量(辅)">
                        <template slot-scope="scope">
                            <span v-if="scope.row.amount">
                                {{ scope.row.amount || '--' }}{{ scope.row.materialId ?
        materialObj[scope.row.materialId].unit :
        "" }}
                            </span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dealName" label="处理人"></el-table-column>
                    <el-table-column prop="materialRecordDate" label="用药时间"></el-table-column>
                    <el-table-column v-if="addEditFlag !== 'addAgain'" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" @click="handleClickEidt(scope.row)">编辑</el-button>
                            <el-button type="text" class="errorText"
                                @click="handleClickDel(scope.row.diseaseRecordDetailId)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <SaveDraftBox ref="saveDraft" v-if="addEditFlag == 'add' && dialogVisible" :formData="ruleForm"
                @pushData="pushData">
            </SaveDraftBox>
            <el-button type="primary" v-show="!ruleForm.inputPondId" @click="submitForm">确 定</el-button>
        </span>
        <el-dialog title="编辑药品" :visible.sync="editDialogVisible" width="30%" :before-close="handleCloseEdit"
            append-to-body>
            <el-form ref="editform" :model="editform" :rules="rules" label-width="120px" class="demo-ruleForm">
                <el-form-item label="药品名称" prop="materialId">
                    <el-input v-model="editform.materialName" disabled></el-input>
                </el-form-item>
                <el-form-item label="投喂量(主)" prop="convertNum">
                    <el-input v-model="editform.convertNum" @change="handleChangeconvertNum(editform)">
                        <template slot="append">{{ editform.materialId ? materialObj[editform.materialId].aUnit :
        "" }}</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="投喂量(辅)" prop="amount">
                    <el-input v-model="editform.amount" @change="handleChangeNum(editform)">
                        <template slot="append">{{ editform.materialId ? materialObj[editform.materialId].unit :
        "" }}</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="处理人" prop="dealId">
                    <el-select v-model="editform.dealId" filterable clearable class="w100p"
                        @change="(id) => { handleChangeStaff(id, 'dealName') }">
                        <el-option v-for="item, index in staffList" :key="index" :label="item.staffName"
                            :value="item.staffId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="处理日期" prop="materialRecordDate">
                    <el-date-picker v-model="editform.materialRecordDate" value-format="yyyy-MM-dd" type="date"
                        placeholder="选择日期" :picker-options="pickerOptions" class="w100p">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEditForm">确 定</el-button>
            </span>
        </el-dialog>
    </el-dialog>
</template>
<script>
import store from "@/store";
import diseaseRecords from '@/api/disease-prevention-and-control/disease-records.js';
import pondStockingManagement from '@/api/production-management/pond-stocking-management.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        fishPondList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
        diseaseList: {
            type: Array,
            default: () => {
                return []
            }
        },
        staffList: {
            type: Array,
            default: () => {
                return []
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let checkNum = (rule, value, callback) => {
            if (value) {
                if (Number(value) > 0 && Number(value) <= 99999) {
                    callback();
                } else if (Number(value) > 99999) {
                    callback(new Error('请输入小于100000的数'));
                } else {
                    callback(new Error('请输入大于0的数'));
                }
            } else {
                callback(new Error('请输入数值'));
            }
        };
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() >= Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            editform: {},
            editDialogVisible: false,
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            fishVarietyList: [],
            detailList: [],
            rules: {
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                amount: [
                    { required: true, validator: checkNum, trigger: 'change' }
                ],
                dealDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                fishPondId: [
                    { required: true, message: '请选择鱼塘', trigger: 'change' }
                ],
                dealId: [
                    { required: true, message: '请选择处理人', trigger: 'change' }
                ],
                fishVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                materialId: [
                    { required: true, message: '请选择品种规格', trigger: 'change' }
                ],
                convertNum: [
                    { required: true, message: '请输入数量', trigger: 'change' }
                ],
                findNameId: [
                    { required: true, message: '请选择发现人', trigger: 'change' }
                ],
                findDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                materialRecordDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
            }
        }
    },
    computed: {},
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },
    computed: {
        materialObj() {
            return store.state.basicData.material;
        }
    },
    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'addAgain') {
                this.ruleForm = { ...this.data }
                this.addEditApi = diseaseRecords.addAgain
                this.addEditName = '继续处理';
                this.diseaseRecordsDetail(this.data.diseaseRecordsId)
                this.$set(this.ruleForm, 'medicineList', [{
                    convertNum: null, amount: null, materialId: null, materialName: null
                }])
            }
            else if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = diseaseRecords.add
                this.addEditName = '添加';
                this.getInitRulFormData();
                this.$set(this.ruleForm, 'medicineList', [{
                    convertNum: null, amount: null, materialId: null, materialName: null
                }])
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = { ...this.data }
                this.addEditApi = diseaseRecords.edit
                this.addEditName = '编辑';
                this.batchPondInfoList(this.data.batchId);
                this.diseaseRecordsDetail(this.data.diseaseRecordsId)
                this.getInitRulFormData();
                if (this.ruleForm.medicineList && Array.isArray(this.ruleForm.medicineList)) {
                    this.$set(this.ruleForm, 'medicineList', this.ruleForm.medicineList)
                } else {
                    this.$set(this.ruleForm, 'medicineList', [{
                        convertNum: null, amount: null, materialId: null, materialName: null
                    }])
                }
            }
        },
        
        pushData(data) {
            this.ruleForm = { ...data };
            this.batchPondInfoList(this.ruleForm.batchId);
            this.diseaseRecordsDetail(this.ruleForm.diseaseRecordsId)
            this.$nextTick(() => {
                this.$refs.ruleForm.clearValidate();
            })
        },
        submitEditForm() {
            this.$refs.editform.validate((valid) => {
                if (valid) {
                    let rut = this.staffList.find(item => item.staffId == this.editform.dealId);
                    let dealName = rut?.staffName
                    console.log(dealName,this.editform.dealId)
                    diseaseRecords.editDetailDel({ ...this.editform,dealName:dealName }).then(res => {
                        if (res.success) {
                            this.editform = {};
                            this.editDialogVisible = false;
                            this.$message.success('操作成功')
                            this.diseaseRecordsDetail(this.ruleForm.diseaseRecordsId)
                        } else {
                            this.$message.warning('操作失败')
                        }
                    }).catch(err => {
                        this.$message.warning('操作失败')
                    })
                } else {
                    return false;
                }
            })
        },
        handleClickDel(id) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                diseaseRecords.detailDel(id).then(res => {
                    if (res.success) {
                        this.$message.success('删除成功');
                        this.diseaseRecordsDetail(this.ruleForm.diseaseRecordsId)
                    }
                }).catch(err => {
                    this.$message.error(err);
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleClickEidt(row) {
            console.log(this.materialObj, row)
            this.editform = {
                ...row,
                convertNum: row.amount / this.materialObj[row.materialId].ratioNum
            };
            this.editDialogVisible = true;
        },
        async diseaseRecordsDetail(diseaseRecordsId) {
            if (!diseaseRecordsId) return;
            let { data: detailList } = await diseaseRecords.diseaseRecordsDetail({ diseaseRecordsId });
            this.detailList = detailList || []
        },
        async batchPondInfoList(batchId) {
            if (!batchId) {
                return
            };
            let { data: fishVarietyList } = await pondStockingManagement.batchPondInfoList({ batchId });
            this.fishVarietyList = fishVarietyList || [];
            this.fishVarietyNumObj = {}
            this.fishVarietyList = this.fishVarietyList.filter(item => {
                this.fishVarietyNumObj[item.fishVarietyId] = item.num
                return item.num > 0
            })
        },
        //转换投喂量
        handleChangeNum(row) {
            if (!row.amount) {
                return
            } else {
                let amount = row.amount = Number(row.amount)
                row.convertNum = amount / this.materialObj[row.materialId].ratioNum
            }
        },
        //转换投喂量
        handleChangeconvertNum(row) {
            if (!row.convertNum) {
                return
            } else {
                let convertNum = Number(row.convertNum)
                row.amount = convertNum * this.materialObj[row.materialId].ratioNum
            }
        },
        //添加药品
        addMaterial() {
            let length = this.ruleForm.medicineList?.length || 0
            if (length) {
                this.$set(this.ruleForm.medicineList, length, {
                    convertNum: null, amount: null, materialId: null, materialName: null
                })
            }
        },
        //删除药品
        delMaterial(index) {
            let list = this.ruleForm.medicineList;
            list.splice(index, 1);
            this.$set(this.ruleForm, 'medicineList', list)
        },
        //初始化一些表单数据
        getInitRulFormData() {
            let id = sessionStorage.getItem('staffId') || null;
            let params = {};
            if (this.addEditFlag == 'add') {
                params = {
                    dealId: id == 'null' ? '' : Number(id),
                    findNameId: id == 'null' ? '' : Number(id),
                    dealDate: this.$formatTime(new Date(), 'yyyy-MM-dd'),
                    findDate: this.$formatTime(new Date(), 'yyyy-MM-dd')
                }
            } else if (this.addEditFlag == 'edit') {
                params = {
                    ...this.ruleForm,
                    dealId: id == 'null' ? '' : id,
                    dealDate: this.$formatTime(new Date(), 'yyyy-MM-dd'),
                }
            }
            this.$set(this, 'ruleForm', params);
            setTimeout(() => {
                this.$refs['ruleForm'].clearValidate();
            }, 100)
        },
        //选择鱼塘时提示用户是否存在该关联批次
        handleChangeFishPond(id) {
            let rut = this.batchList.find(item => item.fishPondId == id);
            let batchId = rut?.batchId
            this.$set(this.ruleForm, 'batchId', batchId || '');
            this.batchPondInfoList(batchId)
            !rut && this.$message.warning('该鱼塘暂无批次!');
        },
        //获取称重人姓名
        handleChangeStaff(id, key) {
            let rut = this.staffList.find(item => item.staffId == id);
            let staffName = rut?.staffName
            this.$set(this.ruleForm, key, staffName || '');
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let medicineList = [];
                    if (this.addEditFlag == 'addAgain') {
                        this.ruleForm.medicineList.forEach(item => {
                            item.dealName = this.ruleForm.dealName
                            item.dealId = this.ruleForm.dealId
                        })
                        medicineList = this.ruleForm.medicineList.filter(item => {
                            return !item.diseaseRecordDetailId
                        })
                    } else if (this.addEditFlag == 'edit') {
                        medicineList = JSON.parse(JSON.stringify(this.detailList))
                    } else {
                        this.ruleForm.medicineList.forEach(item => {
                            item.dealName = this.ruleForm.dealName
                            item.dealId = this.ruleForm.dealId
                        })
                        if (this.detailList.length > 0 && this.ruleForm.medicineList.length > 0) {
                            medicineList = this.ruleForm.medicineList.concat(this.detailList)
                        } else {
                            medicineList = this.ruleForm.medicineList
                        }
                    }
                    this.addEditApi({ ...this.ruleForm, medicineList }).then(res => {
                        let msg = res.success ? '操作成功' : '操作失败'
                        this.$message[res.success ? 'success' : 'warning'](res.message || msg)
                        res.success && this.cancel();
                        //提交数据时删除保存的记录
                        res.success && this.addEditFlag == 'add' && this.$refs.saveDraft.delByKey();
                    }).catch(err => {
                        this.$message.error(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.detailList = [];
            this.fishVarietyList = [];
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleCloseEdit(done) {
            this.$confirm('确认关闭？')
                .then(_ => { done() })
                .catch(_ => { });
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
::v-deep .noLabel {
    .el-form-item__content {
        margin: 0 !important;
    }
}

.icon {
    font-size: 24px;
    line-height: 30px;
    margin-left: 15px;
}

.infoList {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;

    .infoItem {
        width: calc(100% / 4 - 10px);
    }

    .label {
        color: #999999;
    }

    .text {
        padding-left: 5px;
        color: rgb(0, 153, 255);
    }
}
</style>